package net.esj.basic.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SQLQuery;
import org.hibernate.type.Type;

public abstract class ScalarMapper {
	
	private String[] names;
	private Type[] types;
	
	public abstract Object mapRow(int num,Object[] resultSet);
	
	public ScalarMapper(String[] names,Type[] types){
		this.names = names;
		this.types = types;
	}
	
	public List execute(SQLQuery query){
		for(int i =0;i<names.length;i++){
			query.addScalar(names[i], types[i]);
		}
		
		int j=0;
		List list = new ArrayList();
		List values = query.list();
		for(Object o : values){
			Object[] resultSet = new Object[0];
			if(o instanceof String){
				resultSet[0] = o;
			}else{
				resultSet = (Object[]) o;
			}
			list.add(mapRow(j,resultSet));
			j++;
		}
		return list;
	}

}
